package com.gelingqin.es.springbootdemo.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import com.gelingqin.es.springbootdemo.entity.Condition;
import com.gelingqin.es.springbootdemo.entity.LogRequest;
import com.gelingqin.es.springbootdemo.entity.Query;
import com.gelingqin.es.springbootdemo.process.BetweenProcess;
import com.gelingqin.es.springbootdemo.process.ConditionProcess;
import com.gelingqin.es.springbootdemo.process.EqualProcess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 日志服务
 * 
 * @author 86133
 *
 */
@Service
public class LogService {

	@Autowired
	private ElasticsearchService elasticsearchService;

	private Map<String, ConditionProcess> processMap = new HashMap<String, ConditionProcess>();

	@PostConstruct
	public void init() {
		//等于
		processMap.put("equal", new EqualProcess());
		//介于
		processMap.put("between", new BetweenProcess());
	}

	/**
	 * 
	 * @param logRequest
	 */
	public List<Map<String, Object>> search(LogRequest logRequest) {
		//设置查询索引模板
		Query query= Query.build(logRequest.getIndexPattern());
		query.setIndexPattern("app-common");
		//开始时间
		query.rangeGte(logRequest.getTimeKey(), logRequest.getStartTime());
		//结束时间
		query.rangeLte(logRequest.getTimeKey(), logRequest.getEndTime());
		//内容
		query.match(logRequest.getContentKey(), logRequest.getSearchWords());
		List<Condition> conditions=logRequest.getConditions();
		//动态查询条件
		if (conditions!=null&&conditions.size()>0) {
			for(Condition condition:conditions){
				ConditionProcess process=processMap.get(condition.getExp());
				if (process!=null) {
					//添加查询条件
					process.process(query, condition);
				}
			}
			
		}
		return elasticsearchService.search(query);
	}
	public List<Map<String, Object>> dateHistgram(LogRequest logRequest){
        //设置查询索引模板
        Query query= Query.build(logRequest.getIndexPattern());
        //开始时间
        query.rangeGte(logRequest.getTimeKey(), logRequest.getStartTime());
        //结束时间
        query.rangeLte(logRequest.getTimeKey(), logRequest.getEndTime());
        elasticsearchService.dateHistgram(query);
	    return  null;
    }

}
